const http = require('http');
const fs = require('fs');

export function downloadFileAsync(uri: string, toFilePath: string) {
    return new Promise((resolve, reject) => {
        // 确保dest路径存在
        const file = fs.createWriteStream(toFilePath);

        http.get(uri, (res) => {
            if (res.statusCode !== 200) {
                reject(res.statusCode);
                return;
            }

            res.on('end', () => {
                console.log('download end');
            });

            // 进度、超时等

            file.on('finish', () => {
                console.log('finish write file')
                file.close(resolve);
            }).on('error', (err) => {
                fs.unlink(toFilePath);
                reject(err.message);
            })

            res.pipe(file);
        });
    });
}